package com.spring.sunflower.base;

import android.util.Log;

import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.spring.sunflower.data.RequestDataSource;

import java.util.Map;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * Created by <b><a style="color:#8BC34A"href="http://blog.csdn.net/student9128">Kevin</a></b> on 2017/5/26.
 * <p>Blog:http://blog.csdn.net/student9128.
 * <p><b>Description:</b>
 * </p >
 */


public class BasePresenter<V extends BaseView> {
    private CompositeDisposable compositeDisposable;
    public V baseView;
    public RequestDataSource requestDataSource;

    public BasePresenter(V baseView) {
        this.baseView = baseView;
        this.requestDataSource = RequestDataSource.getInstance();
    }

    /**
     * 解除绑定
     */
    public void detachView() {
        baseView = null;
        removeDisposable();
    }

    /**
     * 返回 view
     *
     * @return
     */
    public V getBaseView() {
        return baseView;
    }

    public void addDisposable(Observable<?> observable, BaseObserver observer) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(observable.subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(observer));
    }

    public void removeDisposable() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
    }

    public <T> T handleJson(Map<String, Object> data, Class<T> clazzBean) {
        String json = new Gson().toJson(data);
        Log.d("BasePresenter",json);
        T ot = new Gson().fromJson(json, clazzBean);
        return ot;
    }

    public void saveField(String key, String value) {
        SPUtils.getInstance().put(key, value);
    }

    public void saveField(String key, Boolean value) {
        SPUtils.getInstance().put(key, value);
    }

    public void saveField(String key, int value) {
        SPUtils.getInstance().put(key, value);
    }

    public String getField(String key, String defaultValue) {
        return SPUtils.getInstance().getString(key, defaultValue);
    }

    public Boolean getField(String key, Boolean defaultValue) {
        return SPUtils.getInstance().getBoolean(key, defaultValue);
    }
    public int getField(String key, int defaultValue) {
        return SPUtils.getInstance().getInt(key, defaultValue);
    }
}
